<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryWorkOrderParam" class="demo-form-inline">
              <el-form-item label="生产工单名称">
                <el-input
                  v-model="queryWorkOrderParam.WorkOrderName"
                  placeholder="请输入"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchWorkOrder()">搜索</el-button>
              </el-form-item>
              <CustomLoadingIcon />
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addWorkOrder()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionWorkOrder()">批量删除</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              v-loading="tableloading"
              :data="tableData"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="workOrderNO" label="工单编码" width="180">
                <template #default="scope">
                  <el-button type="text" @click="handleProductBillNoClick(scope.row.id)">
                    {{ scope.row.workOrderNO }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="workOrderName" label="工单名称" width="180" />
              <el-table-column prop="orderQuantity" label="订单数量" width="100" align="center" />
              <el-table-column prop="productBill.productBillNo" label="产品编码" width="180" />
              <el-table-column prop="productBill.productBillName" label="产品名称" width="180" />
              <el-table-column prop="productBill.productBillName" label="生产进度" width="160">
                <template v-slot="scope">
                  <el-progress
                    :percentage="scope.row.priority"
                    :color="customColors"
                    :text-inside="true"
                    :stroke-width="24"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="icon" label="优先级" width="120" align="center">
                <template #default="scope">
                  <!-- 0=低，1=中，2=高 -->
                  <el-button type="primary" round size="small" v-if="scope.row.priority === 0">低</el-button>
                  <el-button type="info" round size="small" v-else-if="scope.row.priority === 1">中</el-button>
                  <el-button type="danger" round size="small" v-else-if="scope.row.priority === 2">高</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="icon" label="状态" width="170" align="center">
                <template #default="scope">
                  <!--  状态 选项：0=待生产，1=生产中，2，生产完成，3，已作废，4，暂停 -->
                  <el-button type="info" round size="small" v-if="scope.row.status === 0">待生产</el-button>
                  <el-button type="primary" round size="small" v-else-if="scope.row.status === 1">生产中</el-button>
                  <el-button type="success" round size="small" v-else-if="scope.row.status === 2">生产完成</el-button>
                  <el-button type="info" round size="small" v-else-if="scope.row.status === 3">已作废</el-button>
                  <el-button type="warning" round size="small" v-else-if="scope.row.status === 4">暂停</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="icon" label="来源类型" width="120" align="center">
                <template #default="scope">
                  <el-button type="primary" round size="small" v-if="scope.row.sourceType === 0">客户订单</el-button>
                  <el-button type="success" round size="small" v-else-if="scope.row.sourceType === 1"
                    >库存备货</el-button
                  >
                </template>
              </el-table-column>

              <el-table-column
                prop="estimatedProductionDate"
                label="预计生产日期"
                width="180"
                :formatter="formatColumnTime"
              />
              <el-table-column prop="estimatedEndDate" label="预计结束日期" width="180" :formatter="formatColumnTime" />

              <el-table-column prop="customerCode" label="客户编码" width="180" />
              <el-table-column prop="CustomerName" label="客户名称" width="180" />
              <el-table-column
                prop="actualProductionTime"
                label="实际生产日期"
                width="180"
                :formatter="formatColumnTime"
              />
              <el-table-column prop="actualEndTime" label="实际结束日期" width="180" :formatter="formatColumnTime" />

              <el-table-column prop="creator" label="创建人" width="180" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updator" label="修改人" />

              <el-table-column fixed="right" label="操作" width="190">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteWorkOrderSingle(scope.row.id)">
                    删除
                  </el-button>
                  <!-- <el-button type="primary" plain size="small" @click="UpdateWorkOrder(scope.row)">更新</el-button> -->
                  <el-button type="success" plain size="small" @click="GetProductionTaskSingle(scope.row.id)">
                    查看任务
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="queryWorkOrderParam.PageIndex"
                v-model:page-size="queryWorkOrderParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryWorkOrderParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 功能按钮实现 -->
    <!-- 添加 -->
    <div>
      <!-- 添加工单 -->
      <el-dialog
        v-model="centerDialogVisible"
        :fullscreen="isFullScreen"
        width="66%"
        append-to-body
        :show-close="false"
        :before-close="CreateWorkOrderhandleClose"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">添加工单</span>
            <div class="header-buttons">
              <el-icon @click="toggleFullScreen" class="icon-button">
                <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
              </el-icon>
              <el-icon @click="CreateWorkOrderhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
            </div>
          </div>
        </template>

        <el-scrollbar :max-height="maxHeight + 'px'">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form
                  :inline="true"
                  ref="CreateWorkOrderFormRef"
                  :model="CreateWorkOrderForm"
                  label-width="auto"
                  class="demo-form-inline"
                  :rules="CreateWorkOrderRules"
                >
                  <el-form-item label="工单编号" prop="WorkOrderNO">
                    <el-input
                      v-model="CreateWorkOrderForm.WorkOrderNO"
                      placeholder="不输入则自动生成"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="WorkOrderName" label="工单名称">
                    <el-input
                      v-model="CreateWorkOrderForm.WorkOrderName"
                      placeholder="请输入工单名称"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>

                  <el-form-item label="来源类型">
                    <el-radio-group v-model="CreateWorkOrderForm.SourceType" style="width: 270px">
                      <el-radio value="0">客户订单</el-radio>
                      <el-radio value="1">库存备货</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="产品" prop="ProductBillId">
                    <!-- <el-input v-model="CreateWorkOrderForm.ProductBillId" placeholder="请输入" style="width: 270px">
                    </el-input> -->
                    <el-link style="width: 270px" @click="a">
                      <span
                        v-if="CreateWorkOrderForm.ProductBillId === '' || CreateWorkOrderForm.ProductBillId === null"
                      >
                        <el-icon class="el-icon--left">
                          <el-icon><CirclePlus /></el-icon> </el-icon
                        >选择产品
                      </span>
                      <span v-else> {{ selctCreateWorkOrderForm.productBillName }} </span>
                    </el-link>
                  </el-form-item>
                  <el-form-item label="订单数量" prop="OrderQuantity">
                    <el-input-number
                      v-model="CreateWorkOrderForm.OrderQuantity"
                      :min="1"
                      :max="99999"
                      style="width: 270px"
                      @change="updatehandleUsageRatioChange()"
                    />
                  </el-form-item>
                  <el-form-item label="预计生产日期" prop="EstimatedProductionDate">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="CreateWorkOrderForm.EstimatedProductionDate"
                        type="datetime"
                        placeholder="请选择"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>
                  <el-form-item label="预计结束日期" prop="EstimatedEndDate">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="CreateWorkOrderForm.EstimatedEndDate"
                        type="datetime"
                        placeholder="请选择"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>
                  <el-form-item label="优先级" prop="Priority">
                    <el-segmented
                      style="width: 270px"
                      v-model="CreateWorkOrderForm.Priority"
                      :options="[
                        { label: '高', value: '2' },
                        { label: '中', value: '1' },
                        { label: '低', value: '0' }
                      ]"
                    />
                  </el-form-item>

                  <el-form-item label="客户编码" prop="CustomerNO" v-if="CreateWorkOrderForm.SourceType == 0">
                    <el-input v-model="CreateWorkOrderForm.CustomerNO" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="客户名称" prop="CustomerName" v-if="CreateWorkOrderForm.SourceType == 0">
                    <el-input v-model="CreateWorkOrderForm.CustomerName" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-divider content-position="left">物料列表</el-divider>

            <!-- 产品明细数据表格 -->
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card">
                  <el-tab-pane label="BOM组成">
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="CreateProductcurrentPageData"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column type="selection" width="55" />
                          <el-table-column type="index" label="序号" />
                          <el-table-column prop="MaterialsCode" label="物料编码" />
                          <el-table-column prop="MaterialsName" label="物料名称" />
                          <el-table-column prop="Specification" label="规格" />
                          <el-table-column label="预计使用是" align="center">
                            <template #default="scope">
                              <el-input-number
                                v-model="scope.row.PredictQuantity"
                                :min="1"
                                :max="9999"
                                size="small"
                                :disabled="true"
                              />
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>

                    <!-- 分页 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                          <el-config-provider :locale="zhCn">
                            <el-pagination
                              @size-change="CreateProducthandleSizeChange"
                              @current-change="CreateProducthandleCurrentChange"
                              :current-page="CreateProductcurrentPage"
                              :page-sizes="[10, 20, 50, 100]"
                              :page-size="CreateProductpageSize"
                              layout="total, sizes, prev, pager, next, jumper"
                              :total="CreateProductTotalItems"
                            />
                          </el-config-provider>
                        </div>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="CreateWorkOrderhandleClose">取消</el-button>
            <el-button type="primary" @click="CreateWorkOrderDialog(CreateWorkOrderFormRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择产品信息 -->
      <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectProductBilltableData"
        :dialogVisible="SelectProductBillDialogVisible"
        @selected="handleSelectedProductBillData"
        @closed="handleDialogClosedProductBill"
        @QueryForm="QueryProductBillForms"
      />
    </div>
    <!-- 修改 -->
    <div>
      <!-- 修改工单 -->
      <el-dialog
        v-model="UpdateDialogVisible"
        :fullscreen="isFullScreen"
        width="66%"
        append-to-body
        :show-close="false"
        :before-close="UpdateWorkOrderhandleClose"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">修改工单</span>
            <div class="header-buttons">
              <el-icon @click="toggleFullScreen" class="icon-button">
                <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
              </el-icon>
              <el-icon @click="UpdateWorkOrderhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
            </div>
          </div>
        </template>

        <el-scrollbar :max-height="maxHeight + 'px'">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form
                  :inline="true"
                  ref="UpdateWorkOrderFormRef"
                  :model="UpdateWorkOrderForm"
                  label-width="auto"
                  class="demo-form-inline"
                  :rules="CreateWorkOrderRules"
                >
                  <el-form-item label="工单编号" prop="WorkOrderNO">
                    <el-input
                      v-model="UpdateWorkOrderForm.WorkOrderNO"
                      placeholder="不输入则自动生成"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="WorkOrderName" label="工单名称">
                    <el-input
                      v-model="UpdateWorkOrderForm.WorkOrderName"
                      placeholder="请输入工单名称"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>

                  <el-form-item label="来源类型">
                    <el-radio-group v-model="UpdateWorkOrderForm.SourceType" style="width: 270px">
                      <el-radio :value="0">客户订单</el-radio>
                      <el-radio :value="1">库存备货</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="产品" prop="ProductBillId">
                    <el-link style="width: 270px" @click="UpdateWorkOrderlink">
                      <span> {{ UpdateWorkOrderForm.ProductBill?.productBillName }} </span>
                    </el-link>
                  </el-form-item>
                  <el-form-item label="订单数量" prop="OrderQuantity">
                    <el-input-number
                      v-model="UpdateWorkOrderForm.OrderQuantity"
                      :min="1"
                      :max="99999"
                      style="width: 270px"
                      @change="handleUsageRatioChange()"
                    />
                  </el-form-item>
                  <el-form-item label="预计生产日期" prop="EstimatedProductionDate">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="UpdateWorkOrderForm.EstimatedProductionDate"
                        type="datetime"
                        placeholder="请选择"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>
                  <el-form-item label="预计结束日期" prop="EstimatedEndDate">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="UpdateWorkOrderForm.EstimatedEndDate"
                        type="datetime"
                        placeholder="请选择"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>
                  <el-form-item label="优先级" prop="Priority">
                    <el-segmented
                      style="width: 270px"
                      v-model="UpdateWorkOrderForm.Priority"
                      :options="[
                        { label: '高', value: 2 },
                        { label: '中', value: 1 },
                        { label: '低', value: 0 }
                      ]"
                    />
                  </el-form-item>

                  <el-form-item label="客户编码" prop="CustomerNO" v-if="UpdateWorkOrderForm.SourceType == 0">
                    <el-input v-model="UpdateWorkOrderForm.CustomerNO" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="客户名称" prop="CustomerName" v-if="UpdateWorkOrderForm.SourceType == 0">
                    <el-input v-model="UpdateWorkOrderForm.CustomerName" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-divider content-position="left">物料列表</el-divider>

            <!-- 产品明细数据表格 -->
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card">
                  <el-tab-pane label="BOM组成">
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="UpdateProductcurrentPageData"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column type="selection" width="55" />
                          <el-table-column type="index" label="序号" />
                          <el-table-column prop="MaterialsCode" label="物料编码" />
                          <el-table-column prop="MaterialsName" label="物料名称" />
                          <el-table-column prop="Specification" label="规格" />
                          <el-table-column label="预计使用是" align="center">
                            <template #default="scope">
                              <el-input-number
                                v-model="scope.row.PredictQuantity"
                                :min="1"
                                :max="9999"
                                size="small"
                                :disabled="true"
                              />
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>

                    <!-- 分页 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                          <el-config-provider :locale="zhCn">
                            <el-pagination
                              @size-change="UpdateProducthandleSizeChange"
                              @current-change="UpdateProducthandleCurrentChange"
                              :current-page="UpdateProductcurrentPage"
                              :page-sizes="[10, 20, 50, 100]"
                              :page-size="UpdateProductpageSize"
                              layout="total, sizes, prev, pager, next, jumper"
                              :total="UpdateProductTotalItems"
                            />
                          </el-config-provider>
                        </div>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="UpdateWorkOrderhandleClose">取消</el-button>
            <el-button type="primary" @click="UpdateWorkOrderDialog(UpdateWorkOrderFormRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择产品信息 -->
      <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectProductBilltableData"
        :dialogVisible="UpdateSelectProductBillDialogVisible"
        @selected="UpdatehandleSelectedProductBillData"
        @closed="handleDialogClosedProductBill"
        @QueryForm="QueryProductBillForms"
      />
    </div>

    <!-- 查看任务 -->
    <div>
      <el-dialog v-model="ProductionTaskDialogVisible" width="65%" title="任务列表" append-to-body>
        <el-row>
          <el-col :span="24">
            <el-table
              v-loading="tableloading"
              :data="ProductionTaskData"
              height="300px"
              border
              style="width: 100%"
              max-height="300px"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="productionTaskNO" label="任务编码" width="180" />
              <el-table-column prop="productionTaskName" label="任务名称" width="180" />
              <el-table-column prop="workOrder.workOrderName" label="工单名称" width="180" />
              <!-- <el-table-column prop="productBill.productBillName" label="产品名称" width="180" /> -->
              <el-table-column prop="productBill.productBillName" label="生产进度" width="160">
                <template v-slot="scope">
                  <el-progress :percentage="0" :color="customColors" :text-inside="true" :stroke-width="24" />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="120" align="center">
                <template #default="scope">
                  <el-button type="info" round size="small" v-if="scope.row.status === 0">创建</el-button>
                  <el-button type="primary" round size="small" v-else-if="scope.row.status === 1">生产中</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="schedulingPlan.schedulingPlanName" label="计划名称" width="180" />
              <el-table-column prop="workStation.workStationName" label="站台名称" width="180" />
              <el-table-column prop="userinfo.userName" label="员工" width="180" />
              <el-table-column prop="process.processName" label="工序名称" width="180" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <!-- <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteTeamBillDetialSingle(scope.row.id)">
                    移除
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </el-col>
        </el-row>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="ProductionTaskDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="ProductionTaskDialogVisible = false">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>


<script setup lang="ts">
import CustomLoadingIcon from '../../components/CustomLoadingIcon.vue'
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiGetProduction_WorkOrderPageListAsync,
  ApiDeletionProduction_WorkOrderAsync,
  ApiCreateProduction_WorkOrderAsync,
  ApiGetProduction_WorkOrderByIdAsync,
  ApiUpdateProduction_WorkOrderAsync
} from '../../api/production/ProductionWorkOrderApi'

import {
  ApiGetProductPlanning_ProductBillByIdListAsync,
  ApiGetProductPlanning_ProductBillPageListAsync
} from '../../api/productPlanning/ProductPlanningProductBillApi'
import { ApiGetProduction_ProductionTaskPageListAsync } from '../../api/production/ProductionProductionTaskApi'
import { formatTime, capitalizeFirstLetter } from '../../utils/index'

import ChildComponent from '@/components/CustomSelectDataDialog.vue'

// 定义接口和类型
interface WorkOrderParam {
  WorkOrderName: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}

interface WorkOrder {
  id: string
  ProductBillId: string
  OrderQuantity: number
}

// -------------------------功能按钮------------------------------\

// -------------------------修改------------------------------
//修改使用比例
const handleUsageRatioChange = () => {
  // console.log('前', UpdateMaterialsRouteCraftBillDetial.value)
  // if (UpdateMaterialsRouteCraftBillDetial.value.length > 0) {
  //   UpdateMaterialsRouteCraftBillDetial.value = UpdateMaterialsRouteCraftBillDetial.value.map((item) => ({
  //     ...item,
  //     PredictQuantity: (item.PredictQuantity / UpdateWorkOrderForm.OrderQuantity) * UpdateWorkOrderForm.OrderQuantity
  //   }))
  // }
  // console.log('后', UpdateMaterialsRouteCraftBillDetial.value)
}
// 分页相关数据
const UpdateProductcurrentPage = ref(1)
const UpdateProductpageSize = ref(10)

// 计算当前页要显示的数据
const UpdateProductcurrentPageData = computed(() => {
  const startIndex = (UpdateProductcurrentPage.value - 1) * UpdateProductpageSize.value
  const endIndex = Math.min(startIndex + UpdateProductpageSize.value, UpdateMaterialsRouteCraftBillDetial.value.length)
  return UpdateMaterialsRouteCraftBillDetial.value.slice(startIndex, endIndex)
})

// 总条目数
const UpdateProductTotalItems = computed(() => UpdateMaterialsRouteCraftBillDetial.value.length)

// 处理分页大小变化的方法
const UpdateProducthandleSizeChange = (val: number) => {
  UpdateProductpageSize.value = val
  UpdateProductcurrentPage.value = 1 // 重置页码为 1
}

// 处理当前页变化的方法
const UpdateProducthandleCurrentChange = (val: number) => {
  UpdateProductcurrentPage.value = val
}

//选择产品表格数据
const UpdateSelectProductBillDialogVisible = ref(false)
const UpdateMaterialsRouteCraftBillDetial = ref<ProductBill[]>([])

//选择工序对话框确定操作
const UpdatehandleSelectedProductBillData = (selectedData: ProductBill[]) => {
  if (selectedData && selectedData.length == 1) {
    const row = selectedData
      .map((item) => item.id)
      .values()
      .next().value
    const rowdata = selectedData.values().next().value
    UpdateWorkOrderForm.ProductBillId = rowdata.id
    UpdateWorkOrderForm.ProductBill.productBillName = rowdata.productBillName
    ApiGetProductPlanning_ProductBillByIdListAsync(row).then((res) => {
      UpdateMaterialsRouteCraftBillDetial.value = res.data.data.productPlanningProductBillDetials.map((item: any) => ({
        PredictQuantity: item.usageRatio * UpdateWorkOrderForm.OrderQuantity,
        UsageRatio: item.usageRatio,
        MaterialsId: item.materialsId,
        MaterialsCode: item.materials.materialsCode,
        Specification: item.materials.specification,
        MaterialsName: item.materials.materialsName,
        MeasuringUnitId: item.materials.measuringUnitId
      }))
    })
  } else if (selectedData.length > 1) {
    ElNotification({
      message: '只有选择一条信息，请重新选择',
      offset: 100,
      type: 'warning',
      duration: 2000
    })
  }
}

//打开选择产品对话框
const UpdateWorkOrderlink = () => {
  UpdateSelectProductBillDialogVisible.value = true
  ApiGetProductPlanning_ProductBillPageListAsync(queryProductBillParam).then((res) => {
    SelectProductBilltableData.value = res.data.data
    queryProductBillParam.PageIndex = res.data.pageIndex
    queryProductBillParam.PageSize = res.data.pageSize
    queryProductBillParam.totalCount = res.data.totalCount
  })
}

const UpdateWorkOrderForm = reactive({
  id: '',
  ProductBillId: '',
  ProductBill: { productBillName: '' },
  OrderQuantity: 1
})
const UpdateDialogVisible = ref(false)

// 关闭创建产品对话框
const UpdateWorkOrderhandleClose = () => {
  const formEl = UpdateWorkOrderFormRef.value
  if (!formEl) return
  formEl.resetFields()
  UpdateDialogVisible.value = false //添加对话框状态
  MaterialsRouteCraftBillDetial.value = []

  setTimeout(() => {
    isFullScreen.value = false //添加对话框展开
  }, 300)
}

// 处理 Name 列点击事件
const handleProductBillNoClick = (row: string) => {
  UpdateDialogVisible.value = true

  ApiGetProduction_WorkOrderByIdAsync(row).then((res) => {
    var data = res.data.data
    Object.assign(UpdateWorkOrderForm, capitalizeFirstLetter(data))
    UpdateMaterialsRouteCraftBillDetial.value = data.productionWorkOrderBillDetials.map((item: any) => ({
      PredictQuantity: item.predictQuantity,
      MaterialsId: item.materialsId,
      MaterialsCode: item.materials.materialsCode,
      Specification: item.materials.specification,
      MaterialsName: item.materials.materialsName,
      MeasuringUnitId: item.materials.measuringUnitId
    }))
  })
}

// 确认更新生产工单信息
const UpdateWorkOrderFormRef = ref<FormInstance>()
const UpdateWorkOrderDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      UpdateWorkOrderForm.ProductionWorkOrderBillDetials = UpdateMaterialsRouteCraftBillDetial.value
      console.log('UpdateWorkOrderForm', UpdateWorkOrderForm)

      // ApiUpdateProduction_WorkOrderAsync(UpdateWorkOrderForm).then((res) => {
      //   if (res.data.data) {
      //     ElNotification({
      //       message: '更新成功',
      //       offset: 100,
      //       type: 'success',
      //       duration: 2000
      //     })
      //     UpdateDialogVisible.value = false
      //     SearchWorkOrder()
      //   }
      // })
    }
  })
}

// -------------------------添加------------------------------

//修改使用比例
const updatehandleUsageRatioChange = () => {
  if (MaterialsRouteCraftBillDetial.value.length > 0) {
    MaterialsRouteCraftBillDetial.value = MaterialsRouteCraftBillDetial.value.map((item) => ({
      ...item,
      PredictQuantity: item.UsageRatio * CreateWorkOrderForm.OrderQuantity
    }))
  }
}

//选择的产品from
const selctCreateWorkOrderForm = ref({ id: '' })

//选择工序对话框确定操作
const handleSelectedProductBillData = (selectedData: ProductBill[]) => {
  if (selectedData && selectedData.length == 1) {
    const row = selectedData
      .map((item) => item.id)
      .values()
      .next().value
    selctCreateWorkOrderForm.value = selectedData.values().next().value
    CreateWorkOrderForm.ProductBillId = selctCreateWorkOrderForm.value.id
    ApiGetProductPlanning_ProductBillByIdListAsync(row).then((res) => {
      MaterialsRouteCraftBillDetial.value = res.data.data.productPlanningProductBillDetials.map((item: any) => ({
        PredictQuantity: item.usageRatio * CreateWorkOrderForm.OrderQuantity,
        UsageRatio: item.usageRatio,
        MaterialsId: item.materialsId,
        MaterialsCode: item.materials.materialsCode,
        Specification: item.materials.specification,
        MaterialsName: item.materials.materialsName,
        MeasuringUnitId: item.materials.measuringUnitId
      }))
    })
  } else if (selectedData.length > 1) {
    ElNotification({
      message: '只有选择一条信息，请重新选择',
      offset: 100,
      type: 'warning',
      duration: 2000
    })
  }
}

// 分页相关数据
const CreateProductcurrentPage = ref(1)
const CreateProductpageSize = ref(10)

// 计算当前页要显示的数据
const CreateProductcurrentPageData = computed(() => {
  const startIndex = (CreateProductcurrentPage.value - 1) * CreateProductpageSize.value
  const endIndex = Math.min(startIndex + CreateProductpageSize.value, MaterialsRouteCraftBillDetial.value.length)
  return MaterialsRouteCraftBillDetial.value.slice(startIndex, endIndex)
})

// 总条目数
const CreateProductTotalItems = computed(() => MaterialsRouteCraftBillDetial.value.length)

// 处理分页大小变化的方法
const CreateProducthandleSizeChange = (val: number) => {
  CreateProductpageSize.value = val
  CreateProductcurrentPage.value = 1 // 重置页码为 1
}

// 处理当前页变化的方法
const CreateProducthandleCurrentChange = (val: number) => {
  CreateProductcurrentPage.value = val
}

//选择产品表格数据
const SelectProductBilltableData = ref([])
const SelectProductBillDialogVisible = ref(false)
const MaterialsRouteCraftBillDetial = ref<ProductBill[]>([])

//产品参
interface ProductBill {
  id: string | null
  ProductBillsName: string | null
  ProductClassifyId: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
  UsageRatio: number
}

//打开选择产品对话框
const a = () => {
  SelectProductBillDialogVisible.value = true
  ApiGetProductPlanning_ProductBillPageListAsync(queryProductBillParam).then((res) => {
    SelectProductBilltableData.value = res.data.data
    queryProductBillParam.PageIndex = res.data.pageIndex
    queryProductBillParam.PageSize = res.data.pageSize
    queryProductBillParam.totalCount = res.data.totalCount
  })
}

//选择产品对话框查询操作
const QueryProductBillForms = (form: ProductBill) => {
  ApiGetProductPlanning_ProductBillPageListAsync(form).then((res) => {
    SelectProductBilltableData.value = res.data.data
  })
}

// 对话框关闭后执行的逻辑
const handleDialogClosedProductBill = () => {
  SelectProductBillDialogVisible.value = false
  UpdateSelectProductBillDialogVisible.value = false
}

// 选择产品查询列
const querycolumns = [{ prop: 'ProductBillName', label: '物料名称' }]

// 选择产品列
const columns = [
  { prop: 'productBillNo', label: '物料编码' },
  { prop: 'productBillName', label: '物料名称' },
  { prop: 'measuringUnit.measuringUnitName', label: '计量单位' },
  { prop: 'dimensions', label: '尺寸' },
  { prop: 'model', label: '型号' }
]

// 选择产品查询参数
const queryProductBillParam: ProductBill = reactive({
  id: null,
  ProductBillsName: null,
  ProductClassifyId: null,
  UsageRatio: 1,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

const CreateWorkOrderForm = reactive({ id: '', OrderQuantity: 1, ProductBillId: '' })
// 表单数据和验证规则
const CreateWorkOrderRules = reactive({
  WorkOrderName: [{ required: true, message: '生产工单名称不能为空', trigger: 'blur' }],
  OrderQuantity: [{ required: true, message: '不能为空', trigger: 'blur' }],
  EstimatedProductionDate: [{ required: true, message: '不能为空', trigger: 'blur' }],
  EstimatedEndDate: [{ required: true, message: '不能为空', trigger: 'blur' }]
})
const centerDialogVisible = ref(false)
const CreateWorkOrderFormRef = ref<FormInstance>()

// 关闭创建产品对话框
const CreateWorkOrderhandleClose = () => {
  const formEl = CreateWorkOrderFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false //添加对话框状态
  MaterialsRouteCraftBillDetial.value = []

  setTimeout(() => {
    isFullScreen.value = false //添加对话框展开
  }, 300)
}

// 创建一个响应式变量 maxHeight，初始值为屏幕高度的 80%
const maxHeight = ref(window.innerHeight * 0.6)

// 用于更新 maxHeight 的值
const updateMaxHeight = () => {
  maxHeight.value = window.innerHeight * 0.6
}

// 在组件挂载时添加一个事件监听器，监听窗口大小的变化
onMounted(() => {
  window.addEventListener('resize', updateMaxHeight)
})

// 在组件销毁前移除事件监听器，以防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', updateMaxHeight)
})

const isFullScreen = ref(false)

//展开添加产品窗口
const toggleFullScreen = () => {
  isFullScreen.value = !isFullScreen.value
  if (isFullScreen.value) {
    maxHeight.value = window.innerHeight * 0.8
  } else {
    maxHeight.value = window.innerHeight * 0.6
  }
}

// 打开添加生产工单对话框
const addWorkOrder = () => {
  centerDialogVisible.value = true
}

// 确认添加生产工单
const CreateWorkOrderDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      CreateWorkOrderForm.ProductionWorkOrderBillDetials = MaterialsRouteCraftBillDetial.value
      ApiCreateProduction_WorkOrderAsync(CreateWorkOrderForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateWorkOrderhandleClose()
          SearchWorkOrder()
        }
      })
    }
  })
}

// -------------------------查看任务------------------------------

const ProductionTaskDialogVisible = ref(false)
const ProductionTaskData = ref([])

// 任务查询参数
const queryProductionTaskParam = reactive({
  ProductionTaskName: null,
  WorkOrderId: '',
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 删除单个查看任务
const GetProductionTaskSingle = (id: string) => {
  queryProductionTaskParam.WorkOrderId = id
  ProductionTaskDialogVisible.value = true
  ApiGetProduction_ProductionTaskPageListAsync(queryProductionTaskParam)
    .then((res) => {
      ProductionTaskData.value = res.data.data
    })
    .finally(() => {
      tableloading.value = false
    })
}

// -------------------------删除------------------------------
// 删除单个生产工单
const DeleteWorkOrderSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionWorkOrder()
}

// 批量删除生产工单
const batchDeletionWorkOrder = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionProduction_WorkOrderAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchWorkOrder()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// --------------------------数据列表------------------------------
// 响应式变量
const tableloading = ref(false)
const selectedRows = ref<string[]>([]) // 存储选中的行数据
// 生产进度条颜色
const customColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]
// 查询参数
const queryWorkOrderParam: WorkOrderParam = reactive({
  WorkOrderName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 表格数据
const tableData = ref([])

// 搜索生产工单
const SearchWorkOrder = () => {
  tableloading.value = true
  ApiGetProduction_WorkOrderPageListAsync(queryWorkOrderParam)
    .then((res) => {
      tableData.value = res.data.data
      queryWorkOrderParam.PageIndex = res.data.pageIndex
      queryWorkOrderParam.PageSize = res.data.pageSize
      queryWorkOrderParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 获取用户选择项
const handleSelectionChange = (val: WorkOrder[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  queryWorkOrderParam.PageSize = e
  SearchWorkOrder()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  queryWorkOrderParam.PageIndex = e
  SearchWorkOrder()
}

// 初次加载数据
onMounted(() => {
  SearchWorkOrder()
})
</script>



<style lang="less"  scoped>
@import '../../assets/globle/index.css';

.my-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.icon-button {
  margin-left: 10px;
  cursor: pointer;
}

.full-screen-btn {
  margin-left: 10px;
}
</style>
